/*
 * TelemetryHandler.java is part of htn-example.
 *
 * TelemetryHandler.java is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * TelemetryHandler.java is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with TelemetryHandler.java.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.htn.telescopes.events;

import java.io.IOException;

import ngat.message.GUI_RCS.ReductionInfo;
import ngat.message.GUI_RCS.TELEMETRY_UPDATE_DONE;
import ngat.message.GUI_RCS.TelemetryInfo;
import ngat.net.IConnection;
import ngat.net.camp.CAMPRequestHandler;
import ngat.util.logging.LogManager;
import ngat.util.logging.Logger;
import ngat.util.logging.Logging;

/** 
 * Handles the data returned by the RCS when an observation/group is started, completed, exposes.
 */
public class TelemetryHandler implements CAMPRequestHandler, Logging {

	public static final String CLASS = "TELH";

	/** Default readout time (ms).*/
	private static final long READOUT = 10000L;

	/** Default dprt time (ms).*/
	private static final long DPRT = 5000L;

	/** CAMP Connection used.*/
	IConnection connection;

	/** The encapsulated Telemetry Info.*/
	TelemetryInfo telem;

	/** Class logger. */
	Logger logger = null;

	/** Telescope event listener */
	private LPLTelescopeEventListenerImpl eventlistener;

	/**
	 * Create a TelemetryHandler for the supplied conneciton and telemetry info.
	 * @param connection The Connection to use for reply.
	 * @param telem      The encapsulated Telemetry Info.
	 * @see #logger
	 */
	public TelemetryHandler(LPLTelescopeEventListenerImpl eventlistener, IConnection connection, TelemetryInfo telem) {
		this.connection = connection;
		this.telem = telem;
		this.eventlistener = eventlistener;
		logger = LogManager.getLogger("TRACE");
	}

	/** Returns the handling time - ### fudged.*/
	public long getHandlingTime() {
		return 0L;
	}

	/** Handle an update in form of: ngat.message.GUI_RCS.TelemetryInfo subclass.
	 *
	 * <ul>
	 *  <li> ObservationInfo       : Record start of group - create UH.
	 *  <li> ReductionInfo         : Record one exposure   - add image data to existing UH.
	 *  <li> ObservationStatusInfo : Record end of group   - send the update using info compiled by UH.
	 * </ul>
	 *
	 */
	public void handleRequest() {

		TELEMETRY_UPDATE_DONE done = new TELEMETRY_UPDATE_DONE("TestReply");

		logger.log(INFO, 1, CLASS, "tea", "handleRequest",
				"TELH::Received TelemetryRequest: " + telem);

		if (telem instanceof ReductionInfo) {

			logger.log(INFO, 1, CLASS, "tea", "handleRequest",
					"TELH::This is instance of ReductionInfo.");

			/* Add to TelescopeEventHandler queue */
			eventlistener.addEventMessage((ReductionInfo) telem);

		}

		// send telemetry reply to RCS
		done.setSuccessful(true);
		sendDone(done);

	}

	/** Dispose this handler and close connection from RCS Telemtry sender.*/
	public void dispose() {
		if (connection != null) {
			connection.close();
		}
		connection = null;
		telem = null;
	}

	/** Sends a done message back to client. Breaks conection if any IO errors.*/
	protected void sendDone(TELEMETRY_UPDATE_DONE done) {
		try {
			connection.send(done);
		} catch (IOException iox) {
			logger.log(INFO, 1, CLASS, "tea", "handleRequest",
					"Error sending done: " + iox);
			dispose();
		}
	}

	/** Sends an error message back to client.*/
	protected void sendError(TELEMETRY_UPDATE_DONE done, int errNo,
			String errMsg) {
		done.setErrorNum(errNo);
		done.setErrorString(errMsg);
		sendDone(done);
	}

}
